import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WxWebViewWidget extends StatefulWidget {
  final String url;

  WxWebViewWidget({super.key, required this.url});

  @override
  State<StatefulWidget> createState() => WxWebViewWidgetState();
}

class WxWebViewWidgetState extends State<WxWebViewWidget> {
  late final WebViewController controller;

  // void checkPlatform(WebViewController controller){

  // //用于创建对应平台的控制类
  // late final PlatformWebViewControllerCreationParams params;
  //
  // if (WebViewPlatform.instance is WebKitWebViewPlatform) {
  //   params = WebKitWebViewControllerCreationParams(
  //     allowsInlineMediaPlayback: true,
  //     mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
  //   );
  // } else {
  //   params = const PlatformWebViewControllerCreationParams();
  // }
  //
  // final WebViewController controller = WebViewController.fromPlatformCreationParams(params);
  //
  // if (controller.platform is AndroidWebViewController) {
  //   AndroidWebViewController.enableDebugging(true);
  //   (controller.platform as AndroidWebViewController)
  //       .setMediaPlaybackRequiresUserGesture(false);
  // }
  // }
  final FocusNode focusNode = new FocusNode();
  @override
  void initState() {
    super.initState();
    //初始化Controller
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0xffffff00))
      ..setNavigationDelegate(NavigationDelegate(
          onProgress: (int progress) => print("Progress: $progress"),
          onPageStarted: (String url) {
            print("start visit: $url");
          },
          onPageFinished: (String url) {
            print("finish visit: $url");

            Future.delayed(const Duration(seconds: 5),(){
              controller.runJavaScript("callJS()").then((value) {
                print("flutter call js finished value");
              });
            });
          },
          onWebResourceError: (error) => print("error: ${error.description}"),
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.prevent; //阻止导航 ?? 没生效呢
            // if(request.url.startsWith("https://www.baidu.com")){
            //   return NavigationDecision.prevent;//阻止导航
            // }
            // return NavigationDecision.navigate;//允许导航
          }))
      ..addJavaScriptChannel("TEST", onMessageReceived: (received) {
        print("---->${received.message}");
        showToast(received.message);
        FocusScope.of(context).requestFocus(focusNode);//设置让原有焦点的部件失去焦点
        // FToast
      })
      ..loadHtmlString(testhtml);
    // ..loadRequest(Uri.parse("https://www.baidu.com"));


  }

  void showToast(string){
    Fluttertoast.showToast(msg:string);
  }

  @override
  Widget build(BuildContext context) {
    return WebViewWidget(controller: controller);
  }
}

final testhtml = "<!DOCTYPE html>"
    "<html>"
    "<head>"
    "<meta charset=\"utf-8\">"
    "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no\" />"
    "<title>Local Title</title>"
    "<script>"
    "function callJS(){"
    "alert(\"Android调用了web js\");"
    "}"
    "function callInterface(){"
    "JSCallBackInterface.callback(\"我是web的js哟\");"
    "}"
    "function callInterface2(){"
    "document.location = \"js://Authority?pra1=111&pra2=222\";"
    "}"
    "function clickPrompt(){"
    "TEST.postMessage('Hello');"
    "}"
    "</script>"
    "</head>"
    "<body>"
    "<button type=\"button\" id=\"buttonxx\" onclick=\"callInterface()\">点我调用原生android方法</button>"
    "<button type=\"button\" id=\"buttonxx2\" onclick=\"callInterface2()\">点我调用原生android方法2</button>"
    "<button type=\"button\" id=\"buttonxx3\" onclick=\"clickPrompt()\">点我调用原生android方法3</button>"
    "<input></input>"
    "</body>"
    "</html>";
